﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Yitter.IdGenerator;

namespace Admin.NET.Application;

/// <summary>
/// 原材暂收服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class tentativeService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<tentative> _tentativeRep;
    private readonly SqlSugarRepository<incoming> _incomingRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public tentativeService(SqlSugarRepository<tentative> tentativeRep, ISqlSugarClient sqlSugarClient, SqlSugarRepository<incoming> incomingRep)
    {
        _tentativeRep = tentativeRep;
        _sqlSugarClient = sqlSugarClient;
        _incomingRep = incomingRep;

    }

    /// <summary>
    /// 分页查询原材暂收 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询原材暂收")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<tentativeOutput>> Page(PagetentativeInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _tentativeRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.deliverynumber.Contains(input.Keyword) || u.itemname.Contains(input.Keyword) || u.lotnumber.Contains(input.Keyword) || u.unit.Contains(input.Keyword) || u.Suppliername.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.deliverynumber), u => u.deliverynumber.Contains(input.deliverynumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.itemname), u => u.itemname.Contains(input.itemname.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.lotnumber), u => u.lotnumber.Contains(input.lotnumber.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.unit), u => u.unit.Contains(input.unit.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Suppliername), u => u.Suppliername.Contains(input.Suppliername.Trim()))
            .WhereIF(input.itemcode != null, u => u.itemcode == input.itemcode)
            .WhereIF(input.quantity != null, u => u.quantity == input.quantity)
            .WhereIF(input.suppliercode != null, u => u.suppliercode == input.suppliercode)
            .WhereIF(input.binlocation != null, u => u.binlocation == input.binlocation)
            .WhereIF(input.IncomingtimeRange?.Length == 2, u => u.Incomingtime >= input.IncomingtimeRange[0] && u.Incomingtime <= input.IncomingtimeRange[1])
            .LeftJoin<Partnum>((u, itemcode) => u.itemcode == itemcode.Id)
            .LeftJoin<supplier>((u, itemcode, suppliercode) => u.suppliercode == suppliercode.Id)
            .LeftJoin<warehouselocation>((u, itemcode, suppliercode, binlocation) => u.binlocation == binlocation.Id)
            .Select((u, itemcode, suppliercode, binlocation) => new tentativeOutput
            {
                Id = u.Id,
                deliverynumber = u.deliverynumber,
                itemcode = u.itemcode,
                itemcodeFkDisplayName = $"{itemcode.PartNumCoding}",
                itemname = u.itemname,
                lotnumber = u.lotnumber,
                state = u.state,
                quantity = u.quantity,
                unit = u.unit,
                suppliercode = u.suppliercode,
                suppliercodeFkDisplayName = $"{suppliercode.SuppIierCoding}",
                Suppliername = u.Suppliername,
                binlocation = u.binlocation,
                binlocationFkDisplayName = $"{binlocation.warehouseLocation_name}",
                Incomingtime = u.Incomingtime,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取原材暂收详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取原材暂收详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<tentative> Detail([FromQuery] QueryByIdtentativeInput input)
    {
        return await _tentativeRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加原材暂收 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加原材暂收")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddtentativeInput input)
    {
        var entity = input.Adapt<tentative>();
        incoming incoming = new incoming();  
        incoming.batch=entity.lotnumber;
        incoming.vendor=entity.Suppliername;
        incoming.batchnumber = entity.quantity;
        incoming.Order=YitIdHelper.NextId().ToString();
        incoming.status=false;
      
        var aaa= _incomingRep.InsertAsync(incoming);
        return await _tentativeRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新原材暂收 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新原材暂收")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatetentativeInput input)
    {
        var entity = input.Adapt<tentative>();
        await _tentativeRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除原材暂收 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除原材暂收")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletetentativeInput input)
    {
        var entity = await _tentativeRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _tentativeRep.FakeDeleteAsync(entity);   //假删除
        //await _tentativeRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除原材暂收 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除原材暂收")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletetentativeInput> input)
    {
        var exp = Expressionable.Create<tentative>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _tentativeRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _tentativeRep.FakeDeleteAsync(list);   //假删除
        //return await _tentativeRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatatentativeInput input)
    {
        var itemcodeData = await _tentativeRep.Context.Queryable<Partnum>()
            .InnerJoinIF<tentative>(input.FromPage, (u, r) => u.Id == r.itemcode)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.PartNumCoding}"
            }).ToListAsync();
        var suppliercodeData = await _tentativeRep.Context.Queryable<supplier>()
            .InnerJoinIF<tentative>(input.FromPage, (u, r) => u.Id == r.suppliercode)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.SuppIierCoding}"
            }).ToListAsync();
        var binlocationData = await _tentativeRep.Context.Queryable<warehouselocation>()
            .InnerJoinIF<tentative>(input.FromPage, (u, r) => u.Id == r.binlocation)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.warehouseLocation_name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "itemcode", itemcodeData },
            { "suppliercode", suppliercodeData },
            { "binlocation", binlocationData },
        };
    }
    
    /// <summary>
    /// 导出原材暂收记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出原材暂收记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagetentativeInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExporttentativeOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "原材暂收导出记录");
    }
    
    /// <summary>
    /// 下载原材暂收数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载原材暂收数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExporttentativeOutput>(), "原材暂收导入模板", (_, info) =>
        {
            if (nameof(ExporttentativeOutput.itemcodeFkDisplayName) == info.Name) return _tentativeRep.Context.Queryable<Partnum>().Select(u => $"{u.PartNumCoding}").Distinct().ToList();
            if (nameof(ExporttentativeOutput.suppliercodeFkDisplayName) == info.Name) return _tentativeRep.Context.Queryable<supplier>().Select(u => $"{u.SuppIierCoding}").Distinct().ToList();
            if (nameof(ExporttentativeOutput.binlocationFkDisplayName) == info.Name) return _tentativeRep.Context.Queryable<warehouselocation>().Select(u => $"{u.warehouseLocation_name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入原材暂收记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入原材暂收记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImporttentativeInput, tentative>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 物料编码
                    var itemcodeLabelList = pageItems.Where(x => x.itemcodeFkDisplayName != null).Select(x => x.itemcodeFkDisplayName).Distinct().ToList();
                    if (itemcodeLabelList.Any()) {
                        var itemcodeLinkMap = _tentativeRep.Context.Queryable<Partnum>().Where(u => itemcodeLabelList.Contains($"{u.PartNumCoding}")).ToList().ToDictionary(u => $"{u.PartNumCoding}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.itemcode = itemcodeLinkMap.GetValueOrDefault(e.itemcodeFkDisplayName ?? "");
                            if (e.itemcode == null) e.Error = "物料编码链接失败";
                        });
                    }
                    // 链接 供应商编码
                    var suppliercodeLabelList = pageItems.Where(x => x.suppliercodeFkDisplayName != null).Select(x => x.suppliercodeFkDisplayName).Distinct().ToList();
                    if (suppliercodeLabelList.Any()) {
                        var suppliercodeLinkMap = _tentativeRep.Context.Queryable<supplier>().Where(u => suppliercodeLabelList.Contains($"{u.SuppIierCoding}")).ToList().ToDictionary(u => $"{u.SuppIierCoding}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.suppliercode = suppliercodeLinkMap.GetValueOrDefault(e.suppliercodeFkDisplayName ?? "");
                            if (e.suppliercode == null) e.Error = "供应商编码链接失败";
                        });
                    }
                    // 链接 库位
                    var binlocationLabelList = pageItems.Where(x => x.binlocationFkDisplayName != null).Select(x => x.binlocationFkDisplayName).Distinct().ToList();
                    if (binlocationLabelList.Any()) {
                        var binlocationLinkMap = _tentativeRep.Context.Queryable<warehouselocation>().Where(u => binlocationLabelList.Contains($"{u.warehouseLocation_name}")).ToList().ToDictionary(u => $"{u.warehouseLocation_name}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.binlocation = binlocationLinkMap.GetValueOrDefault(e.binlocationFkDisplayName ?? "");
                            if (e.binlocation == null) e.Error = "库位链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<tentative>>();
                    
                    var storageable = _tentativeRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.deliverynumber?.Length > 64, "送货单号长度不能超过64个字符")
                        .SplitError(it => it.Item.itemname?.Length > 64, "物料名称长度不能超过64个字符")
                        .SplitError(it => it.Item.lotnumber?.Length > 64, "批次号长度不能超过64个字符")
                        .SplitError(it => it.Item.unit?.Length > 32, "单位长度不能超过32个字符")
                        .SplitError(it => it.Item.Suppliername?.Length > 32, "供应商名称长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
